import type { RouterContext } from "@koa/router";
import { RequestException } from "@/error/exception";

export class BaseController {
  assert(v: unknown, code: number, message: string) {
    if (!v) {
      throw new RequestException(message, code, message);
    }
  }
  getBody<T extends object>(ctx: RouterContext) {
    return ctx.request.body as T;
  }
  getQuery<T extends object>(ctx: RouterContext) {
    return ctx.request.query as T;
  }
  getQueryArray(ctx: RouterContext, key: string) {
    const query = ctx.request.query;
    const value = query[`${key}[]`];
    if (!value) {
      return [];
    }
    return Array.isArray(value) ? value : [value];
  }
  getParams<T extends object>(ctx: RouterContext) {
    return ctx.params as T;
  }
  getUser<T extends object>(ctx: RouterContext) {
    return ctx.state.user as T;
  }
  hasUserPermission(ctx: RouterContext) {
    return ctx.state.hasUserPermission as (permissions: string[]) => boolean;
  }
}
